package com.wmsafe.auth.service.impl;

import com.wmsafe.auth.service.LoginServcie;
import com.wmsafe.auth.utils.RedisCache;
import com.wmsafe.auth.entity.LoginUser;
import com.wmsafe.common.entity.SysUser;
import com.wmsafe.common.utils.JwtUtil;
import com.wmsafe.common.utils.ResponseData;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginServcie {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisCache redisCache;

    @Override
    public ResponseData login(SysUser sysUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                sysUser.getUserName(), sysUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getSysUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId,userId,null);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        //把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseData(200,map,"登陆成功");
    }

    @Override
    public ResponseData logout(String userId) {
        //删除redis中的值
        redisCache.deleteObject("login:"+userId);
        return new ResponseData(200,null,"注销成功");
    }
}
